package com.yet.container.remote.netty.client;

import org.springframework.core.Ordered;

import com.yet.container.registry.RegistryMeta.Address;
import com.yet.container.remote.ResponseCallback;
import com.yet.container.remote.ResponseFuture;
import com.yet.dto.Request;
import com.yet.exception.RemotingException;
import com.yet.serialization.Serialization;

public class NettyClient implements Client {

	private final NettyClientProxy nettyClientProxy;

	private final Address address;

	private final Serialization serialization;

	private ResponseCallback responseCallback;

	public NettyClient(Address address, Serialization serialization) {
		this.nettyClientProxy = new NettyClientProxy(address, serialization);
		try {
			nettyClientProxy.initChannel();
		} catch (InterruptedException e) {
			throw new RemotingException("Client启动失败：" + address, e);
		}
		this.address = address;
		this.serialization = serialization;
	}

	@Override
	public ResponseFuture send(Request request) throws RemotingException {
		nettyClientProxy.send(request);
		return new ResponseFuture(request);
	}

	@Override
	public void start() {
		throw new IllegalStateException("不支持手动启动");
	}

	@Override
	public void stop() {
		nettyClientProxy.close();
	}

	@Override
	public int getOrder() {
		return Ordered.HIGHEST_PRECEDENCE + 200;
	}

	public ResponseCallback getResponseCallback() {
		return responseCallback;
	}

	public void setResponseCallback(ResponseCallback responseCallback) {
		this.responseCallback = responseCallback;
	}

	public NettyClientProxy getNettyClientProxy() {
		return nettyClientProxy;
	}

	public Address getAddress() {
		return address;
	}

	public Serialization getSerialization() {
		return serialization;
	}

}
